package com.mspbots.web.converter;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import io.r2dbc.postgresql.codec.Json;
import lombok.extern.log4j.Log4j2;
import org.springframework.core.convert.converter.Converter;
import org.springframework.data.convert.ReadingConverter;
import org.springframework.lang.Nullable;

import java.util.Set;

/**
 * com.mspbots.web.security.converter.UserReadConverter
 *
 * @author Alex bob(https://github.com/vnobo)
 * @date Created by 2019/12/17
 */
@Log4j2
@ReadingConverter
public class SetReadConverter implements Converter<Json, Set<Object>> {

    private final ObjectMapper objectMapper;

    public SetReadConverter(ObjectMapper objectMapper) {
        this.objectMapper = objectMapper;
    }

    @Nullable
    @Override
    public Set<Object> convert(Json source) {
        try {
            return this.objectMapper.readValue(source.asString(), new TypeReference<Set<Object>>() {
            });
        } catch (JsonProcessingException e) {
            log.error("Converter read database set json is error. msg: {}", e.getMessage());
            return Set.of();
        }
    }
}
